<template>
	<div class="app-container">
		<div ref="box1" class="flex-center margin-bottom-10">
			<el-radio-group v-model="searchParams.openingState" size="medium" class="item-gap" @change="onOpeningStateChange">
				<el-radio-button v-for="item in openStateList" :key="item.id" :label="item.id">
					<el-badge v-if="item.id < 4 && item.count > 0" :value="item.count" :max="99">
						<span class="margin-right-20">{{ item.operationName }}</span>
					</el-badge>
					<div v-else class="margin-right-10" style="padding-bottom: 2px;">{{ item.operationName }}</div>
				</el-radio-button>
			</el-radio-group>
		</div>
		<jk-operation-card ref="box2" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-select v-model="searchParams.workshopId" :option-list="workshopList" placeholder="区域" :clearable="false" size="small" class="search-bar-item-size2 margin-5-0 item-gap"></jk-select>
					<jk-select v-model="searchParams.processCode" :option-list="processList" value-key-name="code" placeholder="工序" clearable size="small" style="width: 80px;" class="margin-5-0 item-gap"></jk-select>
					<div class="item-gap"><el-button :disabled="![1,2].includes(searchParams.openingState) || !checkArr.length" icon="el-icon-video-play" size="small" type="success" plain @click="onBatchOpenBtn">开台</el-button></div>
					<div class="item-gap"><el-button :disabled="searchParams.openingState !== 3 || !checkArr.length" icon="el-icon-video-pause" size="small" type="danger" plain @click="onBatchCloseBtn">了机</el-button></div>
				</div>
				<div class="flex-end-center-wrap">
					<jk-search-input v-model="searchParams.productOrderCode" placeholder="生产订单" size="small" class="search-bar-item-code margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-input v-model="searchParams.productNameOrCode" placeholder="品种名称" size="small" class="search-bar-item-size3 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="机台名称" size="small" class="search-bar-item-size1 margin-5-0 item-gap" clearable @on-search="onSearchBtn" />
					<jk-search-button class="item-gap" @click="onSearchBtn"></jk-search-button>
					<jk-more-search class="item-gap" @on-confirm="onSearchBtn" @on-reset="onResetSearchBtn">
						<el-row :gutter="16" class="flex-start-center-wrap">
							<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.batchCode" placeholder="批号" size="small" class="width-100-percent margin-5-0" clearable @on-enter="onSearchBtn" />
							</el-col>
							<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.prdNoticeCode" placeholder="生产通知单号" size="small" class="width-100-percent margin-5-0" clearable @on-enter="onSearchBtn" />
							</el-col>
							<el-col :span="12">
								<el-checkbox v-model="moreSearchParams.ifTest" label="试产打样" border class="width-100-percent" size="small"></el-checkbox>
							</el-col>
							<el-col :span="12">
								<jk-search-input v-model="moreSearchParams.code" placeholder="任务单号" size="small" class="width-100-percent margin-5-0" clearable @on-enter="onSearchBtn" />
							</el-col>
							<el-col :span="12">
								<jk-select v-model="moreSearchParams.priorityId" :option-list="priorityList" placeholder="优先级" clearable size="small" class="margin-5-0 width-100-percent"></jk-select>
							</el-col>
						</el-row>
					</jk-more-search>
					<el-dropdown trigger="click" @command="onJump">
						<el-button type="primary" size="small" class="el-dropdown-link">
							大屏<i class="el-icon-arrow-down el-icon--right"></i>
						</el-button>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item command="foreBigScreen">前纺大屏</el-dropdown-item>
							<el-dropdown-item command="afterBigScreen">后纺大屏</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				ref="jkTable"
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 10"
				@checkbox-change="onCheckBoxChange"
			>
				<vxe-column type="checkbox" fixed="left" width="60" align="center"></vxe-column>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<jk-common-status v-if="item.keyName === 'auditState'" :status="scope.row.auditState"></jk-common-status>
						<jk-state-bar v-else-if="item.keyName === 'openingState'" :state="scope.row.openingState" :state-list="openStateList"></jk-state-bar>
						<jk-state-bar v-else-if="item.keyName === 'priorityName'" :state="scope.row.priorityId" :state-list="priorityList"></jk-state-bar>
						<span v-else-if="item.keyName === 'ifTest'">{{ scope.row.ifTest ? '试产打样' : '正式生产' }}</span>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="244">
					<template slot-scope="scope">
						<div class="flex-center">
							<div class="item-gap"><el-button icon="el-icon-video-play" :disabled="![1, 2].includes(scope.row.openingState)" size="mini" type="success" @click="onOpenBtn(scope.row)">开台</el-button></div>
							<div class="item-gap"><el-button icon="el-icon-video-pause" :disabled="scope.row.openingState !== 3" size="mini" type="danger" @click="onCloseBtn(scope.row)">了机</el-button></div>
							<el-dropdown trigger="click" @command="onDropdownChange($event, scope.row)">
								<el-button type="primary" size="mini" class="el-dropdown-link">
									更多<i class="el-icon-arrow-down el-icon--right"></i>
								</el-button>
								<el-dropdown-menu slot="dropdown">
									<el-dropdown-item
										v-for="(item) in dropdownOption"
										:key="item.code"
										:command="item.code"
										:disabled="item.allowState || item.allowState === 0 ? scope.row.openingState !== item.allowState : false"
										:style="{
											'text-decoration': getPermission([`${prefix}:${item.permissionName}`]) ? '' : 'line-through',
											display: !item.isShow ? 'none' : 'block'
										}"
									>
										<span :class="`${item.icon} item-gap`"></span>
										<span>{{ item.name }}</span>
									</el-dropdown-item>
								</el-dropdown-menu>
							</el-dropdown>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box3" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<open-dialog
			:operation-type="2"
			:select-machine-item="selectMachineItem"
			:dialog-state="openDialogState"
			@on-visible-change="onVisibleChangeOfOpenDialog"
			@on-confirm="onConfirmChangeOfOpenDialog"
		></open-dialog>
		<close-dialog
			:select-machine-item="selectMachineItem"
			:dialog-state="closeDialogState"
			@on-visible-change="onVisibleChangeOfCloseDialog"
			@on-confirm="onConfirmChangeOfCloseDialog"
		></close-dialog>
		<open-again-dialog
			:operation-type="2"
			:select-machine-item="selectMachineItem"
			:dialog-state="openAgainDialogState"
			@on-visible-change="onVisibleChangeOfOpenAgainDialog"
			@on-confirm="onConfirmChangeOfOpenAgainDialog"
		></open-again-dialog>

		<batch-open-dialog
			:machine-list="checkArr"
			:dialog-state="batchOpenDialogState"
			@on-visible-change="onVisibleChangeOfBatchOpenDialog"
			@on-confirm="onConfirmChangeOfBatchOpenDialog"
		></batch-open-dialog>
		<batch-close-dialog
			:machine-list="checkArr"
			:dialog-state="batchCloseDialogState"
			@on-visible-change="onVisibleChangeOfBatchCloseDialog"
			@on-confirm="onConfirmChangeOfBatchCloseDialog"
		></batch-close-dialog>
	</div>
</template>

<script>
    import { auditStateList } from '@/utils/jk/status-option-list';
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import { openStateList, orderPriorityList } from '../../../utils/jk/status-option-list';
    import {
        productionPrdNoticeMachineChangeClearRenovation, productionPrdNoticeMachineChangeDelete,
        productionPrdNoticeMachineChangeGetStateCount,
        productionPrdNoticeMachineChangePostPage
    } from '../../../api/production/xsRenovateOrder';
    import closeDialog from './components/close-dialog';
    import openDialog from './components/open-dialog';
    import batchOpenDialog from './components/batch-open-dialog';
    import batchCloseDialog from './components/batch-close-dialog';
    import openAgainDialog from './components/open-agai-dialog';
    import permissionMixin from '../../../mixins/permission-mixin';
    import {
        productionPrdNoticeMachineClearOpeningOpening,
        productionPrdNoticeMachineCloseClearClose
    } from '../../../api/production/xsOpen';
    export default {
        name: 'ProductOpenCloseMachine',
        components: {
            batchCloseDialog,
            batchOpenDialog,
            closeDialog,
            openDialog,
            openAgainDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache, permissionMixin],
        data() {
            return {
                prefix: 'production:prdNoticeMachineChange',
                apiItem: {
                    'page': productionPrdNoticeMachineChangePostPage
                },
                moreSearchParams: {
                    code: '',
                    prdNoticeCode: '',
                    batchCode: '',
                    priorityId: null,
                    ifTest: false
                },
                batchOpenDialogState: false,
                batchCloseDialogState: false,
                openAgainDialogState: false,
                closeDialogState: false,
                openDialogState: false,
                selectMachineItem: {},
                processList: [],
                workshopList: [],
                openStateList: [
                    ...openStateList,
                    { id: -1, name: '全部', operationName: '全部' }
                ],
                auditStateList: auditStateList,
                dataId: null,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                checkArr: [],
                totalCount: 0,
                priorityList: orderPriorityList,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    productOrderCode: '',
                    machineNameOrCode: '',
                    productNameOrCode: '',
                    processCodes: [],
                    processCode: '',
                    batchCode: '',
                    openingState: 2,
                    workshopId: null
                },
                dropdownOption: [
                    { code: 'DELETE', name: '删除', isShow: true, permissionName: 'delete', icon: 'el-icon-delete', allowState: 1, api: productionPrdNoticeMachineChangeDelete },
                    { code: 'MODIFY_SPIN_COUNT', name: '修改锭数', isShow: true, permissionName: 'update', icon: 'el-icon-view', allowState: 3, api: null },
                    { code: 'CANCEL_RENOVATION', name: '取消翻改', permissionName: 'update', isShow: true, icon: 'el-icon-circle-close', allowState: 2, api: productionPrdNoticeMachineChangeClearRenovation },
                    { code: 'CANCEL_OPEN', name: '取消开台', permissionName: 'update', isShow: true, icon: 'el-icon-circle-close', allowState: 3, api: productionPrdNoticeMachineClearOpeningOpening },
                    { code: 'CANCEL_CLOSE', name: '取消了机', isShow: true, permissionName: 'update', icon: 'el-icon-close', allowState: 4, api: productionPrdNoticeMachineCloseClearClose }
                    // { code: 'QUERY', name: '详情', isShow: true, permissionName: 'query', icon: 'el-icon-view', allowState: null, api: null }
                ]
            };
        },
        methods: {
            onOpeningStateChange() {
                this.searchParams.pageNo = 1;
                this.getListRequest();
            },
            onJump(path) {
                this.$router.push({
                    name: path
                });
            },
            onConfirmChangeOfBatchCloseDialog() {
                this.batchCloseDialogState = false;
                this.getListRequest();
            },
            onBatchCloseBtn() {
                this.batchCloseDialogState = true;
            },
            onVisibleChangeOfBatchCloseDialog(e) {
                this.batchCloseDialogState = e;
            },
            onBatchOpenBtn() {
                this.batchOpenDialogState = true;
            },
            onConfirmChangeOfBatchOpenDialog() {
                this.batchOpenDialogState = false;
                this.getListRequest();
            },
            onVisibleChangeOfBatchOpenDialog(e) {
                this.batchOpenDialogState = e;
            },
            onCheckBoxChange({ records }) {
                this.checkArr = records.filter(x => !x._disabled).map(x => {
                    return x;
                });
            },
            onOpenBtn(row) {
                this.selectMachineItem = row;
                this.openDialogState = true;
            },
            onCloseBtn(row) {
                this.selectMachineItem = row;
                this.closeDialogState = true;
            },
            onConfirmChangeOfOpenAgainDialog() {
                this.openAgainDialogState = false;
                this.getListRequest();
            },
            onVisibleChangeOfOpenAgainDialog(e) {
                this.openAgainDialogState = e;
            },
            onVisibleChangeOfCloseDialog(e) {
                this.closeDialogState = e;
            },
            onConfirmChangeOfCloseDialog() {
                this.closeDialogState = false;
                this.getListRequest();
            },
            onConfirmChangeOfOpenDialog() {
                this.openDialogState = false;
                this.getListRequest();
            },
            onVisibleChangeOfOpenDialog(e) {
                this.openDialogState = e;
            },
            onResetSearchBtn() {
                Object.assign(this.$data.moreSearchParams, this.$options.data().moreSearchParams);
            },
            onDropdownChange(type, row) {
                const optionItem = this.dropdownOption.find(x => x.code === type);
                if (optionItem) {
                    if (optionItem.code === 'QUERY') {
                        this.onDetailBtn({ id: row.id });
                    } else if (optionItem.code === 'MODIFY_SPIN_COUNT') {
                        this.selectMachineItem = row;
                        this.openAgainDialogState = true;
                    } else {
                        if (this.getPermission([`${this.prefix}:${optionItem.permissionName}`])) {
                            this.$confirm(`确定"${optionItem.name}"吗？`, '提示', { type: 'warning' }).then(() => {
                                optionItem.api({ id: row.id }).then(res => {
                                    if (res.data.status === 200) {
                                        this.getListRequest();
                                    }
                                });
                            }).catch(() => {});
                        } else {
                            tipsBar(this, 'custom', 'warning', '无操作权限!');
                        }
                    }
                }
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            onDetailBtn(e) {
                this.dataId = e.id;
            },
            getStateBarCountRequest(params) {
                productionPrdNoticeMachineChangeGetStateCount({
                    workshopId: params.workshopId,
                    processCodes: params.processCodes
                }).then(res => {
                    if (res.data.status === 200) {
                        this.openStateList = this.openStateList.map(x => {
                            x.count = 0;
                            res.data.res.forEach(k => {
                                if (x.id === k.openingState) {
                                    x.count = k.count;
                                }
                            });
                            return x;
                        });
                    } else {
                        this.openStateList = this.openStateList.map(x => {
                            x.count = 0;
                            return x;
                        });
                    }
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.checkArr = [];
                this.tableLoading = true;
                const params = { ...JSON.parse(JSON.stringify(this.moreSearchParams)), ...JSON.parse(JSON.stringify(this.searchParams)) };
                delete params.processCode;
                if (params.openingState === -1) {
                    params.openingState = null;
                }
                if (this.searchParams.processCode === 'BT') {
                    params.processCodes = ['BT', 'TB', 'EB', 'MB'];
                } else {
                    params.processCodes = this.searchParams.processCode ? [this.searchParams.processCode] : [];
                }
                this.getStateBarCountRequest(params);
                this.apiItem.page(params).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },
            /** 修改按钮操作 */
            onEditBtn(row) {
                this.dataId = row.id;
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem.delete({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = JSON.parse(JSON.stringify(this.searchParams));
                params.pageNo = null;
                params.pageSize = null;
                this.$confirm('是否确认导出所有设备机型数据项?', { type: 'warning' }).then(() => {
                    this.exportLoading = true;
                    return this.apiItem.exportExcel(params);
                }).then(res => {
                    if (res.data.status === 200) {
                        this.$download.excel(res, `${this.$route.meta.name}.xls`);
                        this.exportLoading = false;
                    }
                }).catch(() => {});
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            async getDependentData() {
                await this.getMenuColumnListRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.processList = this.$store.state.user.userProcess.processList || [];
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            if (!this.searchParams.processCode) {
                this.$set(this.searchParams, 'processCode', this.$store.state.user.userProcess.defaultProcessCode);
            }
            if (!this.searchParams.workshopId) {
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
            }
            this.getDependentData();
        }
    };
</script>
